package com.zfast.forge.handler;

import com.zfast.forge.common.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 全局异常捕获处理
 */
@RestControllerAdvice
@Slf4j
public class ExceptionControllerAdvice {
    BaseResult result = new BaseResult();

    /**
     * 请求参数校验传递的json格式参数校验
     * @author  khy
     * @createTime 2021年5月18日下午5:24:55
     * @param req
     * @param exception
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Object validatedPostException(HttpServletRequest req, MethodArgumentNotValidException exception) {
        String msg = "数据检验不通过";

        BindingResult bindingResult = exception.getBindingResult();
        if(bindingResult.hasErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            //List<String>errorList = fieldErrors.stream().map(e->e.getDefaultMessage()).collect(Collectors.toList());
            Map<String, String> errorMap = fieldErrors.stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            result.setData(errorMap);
            result.setMsg(msg);
            result.setOk(false);
        }

        return result;
    }

    /**
     * 请求参数校验传递的json格式参数校验
     * @author  khy
     * @createTime 2021年5月18日下午5:24:55
     * @param exception
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object BaseException(Exception exception) {
        String msg = "恭喜你发现了开发中的问题,但由于卡牌随机无法复现,对此深表歉意!为此已为您提升50经验,希望您游戏愉快!";
        result.setData(exception.getMessage());
        result.setMsg(msg);
        result.setOk(false);

        return result;
    }
}
